<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="zh-CN">
<head>
    <meta charset="utf-8">
    <title>会议室预约系统</title>
    <link rel="stylesheet" th:href="@{/pear/component/layui/css/layui.css}" media="all">
    <style>
        body {
            font-size: 12px;
        }

        .layui-form-item {
            margin-bottom: 20px; /* 增加表单项之间的间距 */
        }

        .layui-input-block {
            flex-wrap: wrap; /* 允许子元素换行 */
        }

        .layui-inline {
            margin-left: 10px; /* 增加元素之间的间距 */
        }

        .layui-form-label {
            text-align: right; /* 标签文本右对齐 */
            padding-right: 10px; /* 标签右侧增加间距 */
        }

        .layui-input {
            border: 1px solid #d2d2d2; /* 输入框边框颜色 */
            border-radius: 4px; /* 输入框圆角 */
            padding: 5px 10px; /* 输入框内边距 */
        }

        button {
            background-color: #009688; /* 按钮背景颜色 */
            color: white; /* 按钮文字颜色 */
            border: none; /* 按钮无边框 */
            border-radius: 4px; /* 按钮圆角 */
            padding: 5px 10px; /* 按钮内边距 */
            cursor: pointer; /* 鼠标悬停时显示指针 */
        }

        button:hover {
            background-color: #00796b; /* 按钮悬停时背景颜色 */
        }

        .appointment-item {
            margin-bottom: 10px;
            padding: 10px;
            border: 1px solid #d2d2d2;
            border-radius: 4px;
            background-color: #f9f9f9;
            display: flex;
            justify-content: space-between;
            align-items: center;
            width: 60%; /* 设置宽度为100%，或者根据需要设置具体的宽度值 */
            box-sizing: border-box; /* 确保padding和border不会影响宽度 */
            transition: background-color 0.3s ease;
        }

        .appointment-item:hover {
            background-color: #e0e0e0; /* 鼠标悬停时的背景颜色 */
        }

        .appointment-item button {
            margin-left: 10px; /* 按钮与文本之间的间隔 */
            padding: 5px 10px;
            background-color: #ff5722; /* 按钮背景颜色 */
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            line-height: 0.5; /* 调整按钮的行高 */
            transition: background-color 0.3s ease;
        }

        .appointment-item button:hover {
            background-color: #e64a19; /* 按钮悬停时的背景颜色 */
        }
    </style>
</head>
<body>
<form class="layui-form" action="" method="post" style="width: 100%;">
    <div class="layui-form-item">
        <label class="layui-form-label">会议主题：</label>
        <div class="layui-input-block">
            <input type="text" name="purpose" id="theme" required lay-verify="required" placeholder="请输入会议主题"
                   autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">会议室：</label>
        <div class="layui-input-block">
            <select name="location" id="meeting" lay-filter="meeting" class="layui-select">
                <!-- 动态加载会议室选项 -->
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label" style="width: 60px;">频次：</label>
        <div class="layui-input-block" style="display: flex; align-items: center;">
            <div class="layui-inline" style="width: 120px !important">
                <select name="repeatType" id="repeatType" lay-filter="repeatType">
                    <option value="0">一次</option>
                    <option value="1">每天</option>
                    <option value="2">每个工作日</option>
                    <option value="3">每周的星期几</option>
                    <option value="4">每月的第几天</option>
                </select>
            </div>
            <div class="layui-inline" id="monthDate" style="display: none; width: 100px !important;">
                <label style="width: 30px;line-height:38px">第</label>
                <select id="monthDay">
                    <option th:each="day : ${#numbers.sequence(1, 31)}" th:value="${day}" th:text="${day}"></option>
                </select>
            </div>
            <div class="layui-inline" id="weekDate" style="display: none; width: 100px !important; ">
                <label style="width: 80px;line-height: 38px">星期</label>
                <select id="weekDay" style="">
                    <option value="1">一</option>
                    <option value="2">二</option>
                    <option value="3">三</option>
                    <option value="4">四</option>
                    <option value="5">五</option>
                    <option value="6">六</option>
                    <option value="0">日</option>
                </select>
            </div>
            <div class="layui-inline" style="width: 185px; display: flex; align-items: center;">
                <label id="reservationDateLabel" class="layui-form-label" style="width: 60px;">日期：</label>
                <input type="text" name="reservationDate" id="beginDate" required lay-verify="required|reservationDate"
                       placeholder="请选择日期" autocomplete="off" class="layui-input" style="flex: 1;">
            </div>
            <div class="layui-inline" id="endDate" style="display: none; width: 185px; align-items: center;">
                <label style="width: 60px;">结束日期：</label>
                <input type="text" name="repeatEndDate" id="endDateDiv" required lay-verify=""
                       placeholder="请选择结束日期" autocomplete="off" class="layui-input" style="flex: 1;">
            </div>
            <div class="layui-inline" style="width: 185px; display: flex; align-items: center;">
                <label style="width: 42px;">时间:</label>
                <input type="text" name="timeFrame" id="timeFrame" required lay-verify="required｜timeFrame"
                       placeholder=" - " autocomplete="off" class="layui-input">
            </div>
            <div class="layui-inline" style="width: 100px;">
                <button class="layui-btn layui-btn-sm" type="button" id="confirmButton">确定</button>
            </div>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">预约时间：</label>
        <div class="layui-input-block">
            <div id="appointmentInfo"></div>
        </div>
    </div>
    <div class="bottom">
        <div class="button-container">
            <button type="submit" class="layui-btn  layui-btn-sm" lay-submit=""
                    lay-filter="reservation-save">
                <i class="layui-icon layui-icon-ok"></i>
                提交
            </button>
            <button type="reset" class="layui-btn layui-btn-sm">
                <i class="layui-icon layui-icon-refresh"></i>
                重置
            </button>
        </div>
    </div>
</form>
<script th:src="@{/pear/component/jquery/jquery.min.js}"></script>
<script th:src="@{/pear/component/layui/layui.js}"></script>
<script th:inline="javascript">
    layui.use(['form', 'laydate'], function () {
        let form = layui.form;
        let laydate = layui.laydate;
        let baseURL = /*[[@{/}]]*/ '';
        let reservationMax;
        let closeTime;
        //日期范围
        let startDate = laydate.render({
            elem: '#beginDate',
            type: 'date',//设置日期的类型
            theme: '#2c78da',
            min: new Date().getFullYear() + '-' + (new Date().getMonth() + 1) + '-' + (new Date().getDate()),
            done: function (value, date) {
                if (value !== "") {
                    date.month = date.month - 1;
                    endDate.config.min = date;
                } else {
                    endDate.config.min = startDate.config.min;
                }
            },
        });
        let endDate = laydate.render({
            elem: '#endDateDiv',//绑定的控件名称
            type: 'date',//设置日期的类型
            theme: '#2c78da',
            min: new Date().getFullYear() + '-' + (new Date().getMonth() + 1) + '-' + (new Date().getDate() + 1),

            done: function (value, date) {
                if (value !== "") {
                    date.month = date.month - 1;
                    startDate.config.max = date;
                } else {
                    startDate.config.max = endDate.config.max;
                }
            }
        });
        laydate.render({
            elem: "#timeFrame",
            type: "time",
            range: true,
            shortcuts: [
                {
                    text: '09:30 <p style="text-align: center;">到</p> 11:30',
                    value: (function () {
                        let date1 = new Date();
                        date1.setHours(9, 0, 0, 0);
                        let date2 = new Date();
                        date2.setHours(11, 30, 0, 0);
                        return [date1, date2];
                    })
                },
                {
                    text: '13:00 <p style="text-align: center;">到</p> 15:00',
                    value: (function () {
                        let date1 = new Date();
                        date1.setHours(13, 0, 0, 0);
                        let date2 = new Date();
                        date2.setHours(15, 0, 0, 0);
                        return [date1, date2];
                    })
                }
            ]
        });
        // 监听频次选择框
        form.on('select(repeatType)', function (data) {
            let value = data.value;
            if (value === '4') {
                $('#monthDate').css('display', 'flex');
                $('#weekDate').hide();
                $('#endDate').css('display', 'flex');
            } else if (value === '3') {
                $('#monthDate').hide();
                $('#weekDate').css('display', 'flex');
                $('#endDate').css('display', 'flex');
            } else if (value === '0') {
                $('#monthDate').hide();
                $('#weekDate').hide();
                $('#endDate').hide();
            } else if (value === '1' || value === '2') {
                $('#monthDate').hide();
                $('#weekDate').hide();
                $('#endDate').css('display', 'flex');
            }

            // 动态修改reservationDate标签文字
            if (value === '0') {
                $('#reservationDateLabel').text('日期：');
                startDate = laydate.render({
                    elem: '#beginDate',
                    type: 'date',//设置日期的类型
                    theme: '#2c78da',
                    min: new Date().getFullYear() + '-' + (new Date().getMonth() + 1) + '-' + (new Date().getDate()),
                })
            } else {
                $('#reservationDateLabel').text('开始日期：');
            }
        });
        $.ajax({
            url: baseURL + 'meeting/reservation/getMeetByDepartment?departmentId=' + parent.departmentId, // 后端接口地址
            type: 'GET',
            dataType: 'json',
            success: function (data) {
                var select = $('#meeting');
                select.empty().append('<option value="">请选择会议室</option>');
                let room = data.data
                $.each(room, function (index, rooms) {
                    select.append(
                        '<option value="' + rooms.roomId + '">' +
                        rooms.roomName +
                        ' (设备: ' + (rooms.equipmentNameList.length > 0 ? rooms.equipmentNameList.join(', ') : '无') +
                        ', 容量: ' + rooms.capacity +
                        ', 联系人: ' + rooms.contactName +
                        ', 电话: ' + rooms.contactPhone + ')' +
                        '</option>'
                    );
                });
                form.render('select');
            },
            error: function () {
                layer.msg('加载失败', {icon: 2});
            }
        });
        // 监听会议室选择变化
        form.on('select(meeting)', function (data) {
            let selectedRoomId = data.value; // 获得被选中的值
            $.ajax({
                url: baseURL + 'meeting/meetRoom/getMeetingRoomById?roomId=' + selectedRoomId,
                type: 'get',
                success: function (result) {
                    if (result.data.closeTime != null) {
                        closeTime = result.data.closeTime;
                    }
                    if (result.data && result.data.reservationMax) {
                        reservationMax = result.data.reservationMax;
                    } else {
                        reservationMax = 60;
                    }
                    // 重新渲染结束日期的最大值
                    let today = new Date();
                    let maxDate = new Date(today.getFullYear(), today.getMonth(), today.getDate() + reservationMax);
                    endDate.config.max = maxDate;
                    laydate.render({
                        elem: '#endDateDiv',
                        type: 'date',
                        theme: '#2c78da',
                        min: new Date().getFullYear() + '-' + (new Date().getMonth() + 1) + '-' + (new Date().getDate() + 1),
                        max: maxDate.getFullYear() + '-' + (maxDate.getMonth() + 1) + '-' + maxDate.getDate(),
                        done: function (value, date) {
                            if (value !== "") {
                                date.month = date.month - 1;
                                startDate.config.max = date;
                            } else {
                                startDate.config.max = endDate.config.max;
                            }
                        }
                    });
                },
                error: function () {
                    layer.msg('加载失败', {icon: 2});
                }
            });
        });
        let dateCollection = [];
        // 确定按钮点击事件
        $('#confirmButton').on('click', function () {
            let repeatType = $('#repeatType').val();
            let week = $('#weekDay');
            let meeting = $('#meeting').val()
            let weekDay = week.val();
            let monthDay = $('#monthDay').val();
            let startDate = $('#beginDate').val();
            let endDate = $('#endDateDiv').val();
            let timeFrame = $('#timeFrame').val();
            let timeParts = timeFrame.split(' - ');
            let startTime = timeParts[0]; // 开始时间
            let endTime = timeParts[1];
            let appointmentInfo = $('#appointmentInfo');
            let appointmentText = '';
            // 频次为单次时的判断
            if (repeatType === '0') {
                if (!startDate || !timeFrame) {
                    layer.msg('请选择有效日期时间', {
                        icon: 2,
                        time: 2000
                    });
                    return; // 结束方法
                }
                appointmentText = startDate + ' ' + timeFrame;
            } else {
                // 非单次频次的判断
                if (!startDate || !endDate || !timeFrame) {
                    layer.msg('请选择有效日期时间', {
                        icon: 2,
                        time: 2000
                    });
                    return; // 结束方法
                }
            }
            if (endDate != null) {
                // 计算开始日期和结束日期之间的差值
                let start = new Date(startDate);
                let end = new Date(endDate);
                let diffDays = (end - start) / (1000 * 60 * 60 * 24);

                // 判断差值是否不大于最大预约天数
                if (diffDays > reservationMax) {
                    layer.msg('预约时间超出最大预约天数限制，请重新选择结束时间', {
                        icon: 2,
                        time: 2000
                    });
                    return; // 结束方法
                }

                // 检查是否与会议室关闭时间冲突
                if (closeTime != null && closeTime !== undefined) {
                    let close = closeTime.split(' - ');
                    let start1 = new Date(close[0].replace(' ', 'T'));
                    let end1 = new Date(close[1].replace(' ', 'T'));

                    // 把预约的开始和结束时间转换为时间戳
                    let s1 = new Date(start.getTime());
                    let e1 = new Date(end.getTime());

                    // 检查是否与关闭时间冲突
                    if (!(e1 <= start1 || s1 >= end1)) {
                        layer.msg('该会议室在 ' + closeTime + ' 关闭，请重新选择时间', {
                            icon: 2,
                            time: 3000
                        });
                        return;
                    }
                }
            } else {
                // 如果没有结束日期，只检查开始日期是否在关闭时间内
                let start = new Date(startDate);
                if (closeTime != null && closeTime !== undefined) {
                    let close = closeTime.split(' - ');
                    let start1 = new Date(close[0].replace(' ', 'T'));
                    let end1 = new Date(close[1].replace(' ', 'T'));

                    // 检查开始时间是否在关闭时间内
                    if (start >= start1 && start <= end1) {
                        layer.msg('该会议室在 ' + closeTime + ' 关闭，请重新选择时间', {
                            icon: 2,
                            time: 3000
                        });
                        return;
                    }
                }
            }
            switch (repeatType) {
                case '0': // 一次
                    appointmentText = startDate + ' ' + timeFrame;
                    break;
                case '1': // 每天
                    appointmentText = startDate + ' ———— ' + endDate + ' 每天 ' + timeFrame;
                    break;
                case '2': // 每个工作日
                    appointmentText = startDate + ' ———— ' + endDate + ' 每个工作日（周一至周五） ' + timeFrame;
                    break;
                case '3': // 每周的星期几
                    appointmentText = startDate + ' ———— ' + endDate + ' 每周' + week.find('option:selected').text() + ' ' + timeFrame;
                    break;
                case '4': // 每月的第几天
                    appointmentText = startDate + ' ———— ' + endDate + ' 每月第' + monthDay + ' ' + timeFrame;
                    break;
            }
            let day;
            if (repeatType === '3') {
                day = weekDay
            }

            if (repeatType === '4') {
                day = monthDay
            }
            let frequencyVo = {
                reservationData: startDate,
                startTime: startTime,
                endTime: endTime,
                repeatType: repeatType,
                repeatEndData: endDate,
                day: day// 用于周N天的特殊情况以及每个月第N天的特殊情况。
            }
            let appointmentItem = '<div class="appointment-item" data-frequency-vo=\'' + JSON.stringify(frequencyVo) + '\'>' +
                appointmentText +
                ' <button class="layui-btn layui-btn-danger layui-btn-xs" onclick="removeRow(this)">删除</button></div>';
            if (meeting === '') {
                layer.msg('请选择会议室')
            } else {
                $.ajax({
                    url: baseURL + "meeting/reservation/check?roomId=" + meeting,
                    data: JSON.stringify(frequencyVo),
                    dataType: 'json',
                    contentType: 'application/json',
                    type: 'post',
                    success: function (result) {
                        if (result.code === 1000) {
                            dateCollection = result.data
                            appointmentInfo.append(appointmentItem);
                            layer.msg('预约时间已添加', {
                                icon: 1,
                                time: 2000
                            });
                        } else {
                            if (result.data != null) {
                                let conflictingReservation = result.data[0];
                                layer.msg(`预约时间冲突，冲突时间： ${conflictingReservation.reservationData} ${conflictingReservation.startTime} - ${conflictingReservation.endTime}`, {
                                    icon: 2,
                                    time: 5000
                                });
                            } else {
                                layer.msg(result.msg, {
                                    icon: 2,
                                    time: 2000
                                });
                            }

                        }
                    }
                })
            }
        })
        // 删除预约时间
        window.removeRow = function (btn) {
            // 获取当前按钮所在的 div 元素
            let appointmentItem = btn.parentNode;
            let frequencyVo = JSON.parse(appointmentItem.getAttribute('data-frequency-vo'));
            $.ajax({
                url: baseURL + "meeting/reservation/remove",
                data: JSON.stringify(frequencyVo),
                dataType: 'json',
                contentType: 'application/json',
                type: 'post',
                success: function (result) {
                    if (result.code === 1000) {
                        $(btn).parent().remove();
                        dateCollection = result.data
                        layer.msg('预约时间已删除', {
                            icon: 1,
                            time: 2000
                        });
                    } else {
                        layer.msg(result.msg, {
                            icon: 2,
                            time: 2000
                        });
                    }
                }
            })
        };
        // 提交表单
        form.on('submit(reservation-save)', function (data) {
            // 定义一个数组来存储所有 FrequencyVo 对象
            let reservationList = [];
            let roomId = data.field.location
            // 循环遍历 dateCollection，为每个日期创建一个新的 FrequencyVo 对象
            dateCollection.forEach(function (dateItem) {
                let reservation = {
                    purpose: data.field.purpose,
                    reservationData: dateItem.reservationData,
                    startTime: dateItem.startTime,
                    endTime: dateItem.endTime,
                    repeatType: dateItem.repeatType,
                    repeatEndData: dateItem.repeatEndData,
                };
                reservationList.push(reservation);
            });
            $.ajax({
                url: baseURL + 'meeting/reservation/add?roomId=' + roomId,
                data: JSON.stringify(reservationList),
                dataType: 'json',
                contentType: 'application/json',
                type: 'post',
                success: function (result) {
                    if (result.code === 1000) {
                        layer.msg(result.msg, {
                            icon: 1,
                            time: 2000
                        }, function () {
                            parent.layer.close(parent.layer.getFrameIndex(window
                                .name)); //关闭当前页
                            parent.location.reload();
                        });
                    } else {
                        layer.msg(result.msg, {
                            icon: 2,
                            time: 2000
                        });
                    }
                }
            })
            return false;
        });
    });
</script>
</body>
</html>